import { loginApi, userProfileApi } from '@/api/user'
import { getToken, setToken, removeToken, setTimeStamp } from '@/utils/auth'
export default {
  namespaced: true,
  state: {
    token: getToken(),
    userInfo: {}
  },
  mutations: {
    setToken(state, token) {
      state.token = token
    },
    getUser(state, userInfo) {
      state.userInfo = userInfo
    },
    // 清除token
    removeToken(state) {
      state.token = null
      removeToken()
    },
    removeUserInfo(state) {
      state.userInfo = {}
    }
  },
  actions: {
    async login(ctx, data) {
      const res = await loginApi(data)
      console.log(res)
      ctx.commit('setToken', res.token)// 存仓库
      setToken(res.token)// 存本地
      setTimeStamp()
    },
    async getUserInfo(ctx) {
      const res = await userProfileApi()
      console.log(res)
      ctx.commit('getUser', res.userInfo)
    },
    logout(ctx) {
      ctx.commit('removeToken')
      ctx.commit('removeUserInfo')
    }
  }
}
